package com.htao.train.common.controllor;
import cn.hutool.core.util.StrUtil;
import com.htao.train.common.exception.BusinessException;
import com.htao.train.common.resp.CommonResp;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 统一异常处理、数据预处理等
 */
@RestControllerAdvice
public class ControllerExceptionHandler {

    private static final Logger LOG = LoggerFactory.getLogger(ControllerExceptionHandler.class);

    /**
     * 所有异常统一处理
     * @param e
     * @return
     */

    @ExceptionHandler(value = Exception.class)
    public CommonResp exceptionHandler(Exception e) throws Exception {
/*        LOG.info("seata全局事务ID{}", RootContext.getXID());
        if(StrUtil.isNotBlank(RootContext.getXID())){
            throw e;
        }*/
        CommonResp commonResp = new CommonResp();
        LOG.error("系统异常：", e);
        commonResp.setSuccess(false);
        commonResp.setMessage("系统出现异常，请联系管理员");
        return commonResp;
    }

    /**
     * 唯一异常统一处理
     * @param e
     * @return
     */
    @ExceptionHandler(value = DuplicateKeyException.class)
    public CommonResp exceptionHandler(DuplicateKeyException e) {
        CommonResp commonResp = new CommonResp();
        //异常中带有Duplicate entry这类异常进行处理
        LOG.error("唯一键存在：", e);
        commonResp.setSuccess(false);
        commonResp.setMessage("唯一键存在,请重新编辑");
        return commonResp;
    }

    /**
     * 业务统一处理
     * @param e
     * @return
     */
    @ExceptionHandler(value = BusinessException.class)
    public CommonResp exceptionHandler(BusinessException e) {
        CommonResp commonResp = new CommonResp();
        LOG.error("业务异常：{}", e.getE().getDesc());
        commonResp.setSuccess(false);
        commonResp.setMessage(e.getE().getDesc());
        return commonResp;
    }



    /**
     * 校验异常统一处理
     * @param e
     * @return
     */
    @ExceptionHandler(value = BindException.class)
    public CommonResp exceptionHandler(BindException e) {
        CommonResp commonResp = new CommonResp();
        LOG.error("校验异常：{}", e.getBindingResult().getAllErrors().get(0).getDefaultMessage());
        commonResp.setSuccess(false);
        commonResp.setMessage(e.getBindingResult().getAllErrors().get(0).getDefaultMessage());
        return commonResp;
    }

}
